package middleware

import (
	"fresh-shop-gin/utils"
	"time"

	ginzap "github.com/gin-contrib/zap"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

func ZapLogger() gin.HandlerFunc {
	return ginzap.GinzapWithConfig(zap.L(), &ginzap.Config{
		UTC:        true,
		TimeFormat: time.RFC3339,
		Context: ginzap.Fn(func(c *gin.Context) []zap.Field {
			return []zap.Field{
				zap.String("traceId", c.GetString("traceID")),
				zap.String("clientIP", c.ClientIP()),
			}
		}),
	})
}

// 配置api日志
func GinLogger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()
		path := c.Request.URL.Path
		query := c.Request.URL.RawQuery

		// 处理请求
		c.Next()

		latency := time.Since(start)
		logger := utils.GetLogger().With(
			zap.Int("status", c.Writer.Status()),
			zap.String("method", c.Request.Method),
			zap.String("path", path),
			zap.String("query", query),
			zap.String("ip", c.ClientIP()),
			zap.String("user-agent", c.Request.UserAgent()),
			zap.Duration("latency", latency),
		)

		// 记录错误日志
		if len(c.Errors) > 0 {
			logger.Error("request errors",
				zap.Strings("errors", c.Errors.Errors()),
			)
		} else {
			logger.Info("request completed")
		}
	}
}

// 错误恢复中间件（配合zap）
func ZapRecovery() gin.HandlerFunc {
	return ginzap.RecoveryWithZap(zap.L(), true)
}
